package com.cloud.school.bus.teacherhelper.modules;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.BaseErrorListener;
import com.android.support.jhf.network.BaseStateListener;
import com.android.support.jhf.network.ErrorExceptionHandler;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.AsyncHttpRequest;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.network.loopj.android.http.TextHttpResponseHandler;
import com.android.support.jhf.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.android.support.jhf.utils.AndroidManifestUtil;
import com.android.support.jhf.utils.AndroidUniqueSerialNumber;
import com.android.support.jhf.utils.DateUtils;
import com.android.support.jhf.utils.FileUtils;
import com.android.support.jhf.utils.NetworkStatusUtils;
import com.android.support.jhf.onClick.OnClickListener;
import com.android.support.jhf.onClick.OnClickNetworkStatusListener;
import com.baidu.android.pushservice.CustomPushNotificationBuilder;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.cloud.school.bus.teacherhelper.base.activity.BaseActivity;
import com.cloud.school.bus.teacherhelper.base.baidu.baidupush.BaiduPushUtils;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomAlertDialog;
import com.cloud.school.bus.teacherhelper.base.slidingfragment.BaseAboveFragment;
import com.cloud.school.bus.teacherhelper.base.slidingfragment.BaseBehindFragment;
import com.cloud.school.bus.teacherhelper.base.slidingfragment.BaseSlidingFragmentActivity;
import com.cloud.school.bus.teacherhelper.base.utils.AppUserId;
import com.cloud.school.bus.teacherhelper.base.utils.SaveUserOperate;
import com.cloud.school.bus.teacherhelper.include.Version;
import com.cloud.school.bus.teacherhelper.modules.home.HomeFragment;
import com.cloud.school.bus.teacherhelper.modules.login.LoginActivity;
import com.cloud.school.bus.teacherhelper.protocol.baseresponse.BaseJsonHttpResponse;
import com.cloud.school.bus.teacherhelper.protocol.baseresponse.IHttpResponse;
import com.cloud.school.bus.teacherhelper.protocol.classstudent.GetClassinfoRequest;
import com.cloud.school.bus.teacherhelper.protocol.classstudent.GetClassinfoResponse;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.TeacherHelperApplication;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.umeng.update.UmengUpdateAgent;

import android.R.string;
import android.app.AlertDialog;
import android.app.Notification;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.res.Resources;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 教师助手界面
 * 
 * @author lenovo
 * 
 */
public class SlidingActivity extends BaseSlidingFragmentActivity {

	protected TeacherHelperApplication mApplication;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mApplication = (TeacherHelperApplication) this.getApplicationContext();
		
		mApplication.mFlagHome = true;
		
		umengSDKImploded() ;
		setBaiduPush();
	}

	@Override
	protected BaseAboveFragment getAboveFragment() {
		return new HomeFragment();
	}

	@Override
	protected BaseBehindFragment getBehindFragment() {
		return new HomeMenuFragment();
	}

	public void switchContent(Fragment fragment) {
		mContent = fragment;
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.content_frame, fragment).commit();
		getSlidingMenu().showContent();
	}

	public void toggle() {
		getSlidingMenu().toggle();
	}

	public void getClassinfo(final Runnable runnable) {
		if (null == mApplication.mClassInfo || null == mApplication.mTeacher
				|| null == mApplication.mStudentList) {
			NetworkClient.getNetworkClient().GetRequest(
					new GetClassinfoRequest(this), new GetClassinfoResponse() {
						@Override
						public void onResponse(
								ResponseHandlerInterface responseHandlerInterface) {

							if ("1".equals(code)) {
								mApplication.mClassInfo = classInfo;
								mApplication.mTeacher = teacher;
								mApplication.mStudentList = studentList;
								HandlerPostUI.getHandlerPostUI(runnable);
							} else if ("-4".equals(code)) {
								HandlerToastUI.getHandlerToastUI(
										SlidingActivity.this, "不存在班级");
							}
						}
					});
		} else {
			HandlerPostUI.getHandlerPostUI(runnable);
		}
	}

	private void quit() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(this,
				R.style.CustomAlertDialog);
		customAlertDialog.setTitleMessage(getString(R.string.tips), Color.BLACK);
		customAlertDialog.setMessage(getString(R.string.quit_the_application));
		customAlertDialog.setLeftButton(getString(R.string.quit), new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mApplication.mFlagHome = false;
				System.exit(0);
				finish();
			}
		});
		customAlertDialog.setRightButton(getString(R.string.cancel), new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

			}
		});
		customAlertDialog.show();
	}
	
	/**
	 * 设置百度推送
	 */
	private void setBaiduPush(){
		// Push: 以apikey的方式登录，一般放在主Activity的onCreate中。
        // 这里把apikey存放于manifest文件中，只是一种存放方式，
        // 您可以用自定义常量等其它方式实现，来替换参数中的Utils.getMetaValue(PushDemoActivity.this,
        // "api_key")
        // 通过share preference实现的绑定标志开关，如果已经成功绑定，就取消这次绑定
//        if (!BaiduPushUtils.hasBind(getApplicationContext())) {
            PushManager.startWork(getApplicationContext(),
                    PushConstants.LOGIN_TYPE_API_KEY,
                    AndroidManifestUtil.getMetaValue(this, "api_key"));
            // Push: 如果想基于地理位置推送，可以打开支持地理位置的推送的开关
            // PushManager.enableLbs(getApplicationContext());
//        }
        
        Resources resource = this.getResources();
        String pkgName = this.getPackageName();
        
        // Push: 设置自定义的通知样式，具体API介绍见用户手册，如果想使用系统默认的可以不加这段代码
        // 请在通知推送界面中，高级设置->通知栏样式->自定义样式，选中并且填写值：1，
        // 与下方代码中 PushManager.setNotificationBuilder(this, 1, cBuilder)中的第二个参数对应
//        CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
//                getApplicationContext(), resource.getIdentifier(
//                        "notification_custom_builder", "layout", pkgName),
//                resource.getIdentifier("notification_icon", "id", pkgName),
//                resource.getIdentifier("notification_title", "id", pkgName),
//                resource.getIdentifier("notification_text", "id", pkgName));
//        cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
//        cBuilder.setNotificationDefaults(Notification.DEFAULT_SOUND
//                | Notification.DEFAULT_VIBRATE);
//        cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
//        cBuilder.setLayoutDrawable(resource.getIdentifier(
//                "simple_notification_icon", "drawable", pkgName));
//        PushManager.setNotificationBuilder(this, 1, cBuilder);
	}
	
	/**
	 * 友盟sdk集成
	 */
	private void umengSDKImploded() {
		// 自动更新
		UmengUpdateAgent.setUpdateAutoPopup(true);
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(mApplication);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (!getSlidingMenu().isMenuShowing()) {
				getSlidingMenu().showMenu();
			} else {
				quit();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 为了屏蔽父类的这个方法，父类的这个方法作用是按返回键不显示左侧菜单，但是现在需要按下返回键显示左侧菜单
	 */
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		return true;
	}
}
